#include "client.h"

void user_register(int peerfd){
    train_t t;
    memset(&t, 0 ,sizeof(t));
    //发送用户名给register1
    if(register1(peerfd,&t)){
        register2(peerfd,&t);
    }
}
int register1(int peerfd,train_t * t){
    train_t train;
    memset(&train , 0 ,sizeof(train));
    //接受并发送用户名

    printf("please enter your username:");
    char name[512] = {0};
    scanf("%s",name);

    //初始化小火车并发送
    train.len = strlen(name);
    train.type = CMD_TYPE_REGISTER1;
    strcpy(train.buff,name);
    sendn(peerfd,&train,4+4+train.len);
    printf("register1 send %d byte\n",train.len);

    //接受server查找数据库之后的结果,salt/失败CODE
    memset(&train,0,sizeof(train));
    int len = 0;
    CmdType x;
    recvn(peerfd,&len,sizeof(len));
    recvn(peerfd,&x,sizeof(x));
    recvn(peerfd,train.buff,len);
    if(x == CMD_TYPE_REGISTER1_ERROR){
        puts("username already exist!");
        return 0;
    }else{
        memcpy(t,&train,sizeof(train));//t里面的buff存储serve的salt值
        return 1;
    }
}

void register2(int peerfd,train_t * t){
    train_t train;
    memset(&train , 0 ,sizeof(train));
    //根据salt值和密码生成密文发送给服务器
    printf("please enter your password:");
    char password[512] = {0};
    scanf("%s",password);
    //获得client端产生的encrypt,TODO:可能crypt操作方法不同
    char encrypt[512] = {0};
    char * a = crypt(password,t->buff);
    int len = strlen(a);
    memcpy(encrypt,a,len);
    //初始化小火车并发送
    memset(&train, 0, sizeof(train));
    train.len = len;
    train.type = CMD_TYPE_REGISTER2;
    strcpy(train.buff,encrypt);
    sendn(peerfd,&train,4+4+train.len);
    printf("register2  send %d byte\n",train.len);

    //接受server经由对比得到的正确与否消息
    memset(&train,0,sizeof(train));
    len = 0;
    CmdType x;
    recvn(peerfd,&len,sizeof(len));
    recvn(peerfd,&x,sizeof(x));
    recvn(peerfd,train.buff,len);
    if(x == CMD_TYPE_REGISTER2_ERROR){
        puts("have trouble in  password!");
    }else{
        puts("注册成功");
    }
}
